package com.itphy.controller;

import com.itphy.common.R;
import com.itphy.util.FastDFSClient;
import com.itphy.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.extend.cors.annotation.CrossOrigin;

import java.util.Objects;

@Controller
@CrossOrigin
public class HomeController {

    @Inject
    private FastDFSClient fastDFSClient;

    @Mapping(value = "/")
    public ModelAndView qq(){
        return new ModelAndView("imgys.html");
    }

    @Mapping(value = "/oss",method = MethodType.POST)
    public R uploadFile(Context ctx, String code){
        String result =null,
               extension=null;
        try {
            UploadedFile fileObj = ctx.file("file");
            if(!Objects.isNull(fileObj)){
                extension=fileObj.extension;
                if(Objects.isNull(extension)){
                    extension="jpg";
                }
                result = fastDFSClient.uploadFile(FileUtil.InputStreamToByteArray(fileObj.content),extension);
            }
            return R.ok().data(result);
        } catch (Exception e) {
            return R.fail().msg(e.getMessage());
        }
    }

}
